import {getProducts} from '@/services/products'
export default {
  //调用model的时候，通过命名空间调用，不要和其他的model重名
  namespace: 'products',

  // 跟react 中的state类似，和redux中保存的state一样
  state: {
    productList: [],
    size: '',
    shippingCartList: [],
    shippingCartNum: 0,
  },

  // 调用服务端的接口，获取数据
  effects: {
    *fetchProducts({payload, callback}: any, {put, call}: any) {
      // 获取数据
      // @ts-ignore
      const response = yield call(getProducts)
      // 调用reducers更新状态
      yield put ({
        type: 'setProductList', // 类似与redux中action的type
        payload: {
          size: payload,
          productList: payload ?
            response.products?.filter((product: any) => product.availableSizes.includes(payload))
            : response.products
        }
      })

    },
  },
  // 更新state
  reducers: {
    setProductList(state: any, {payload}: any) {
      return {...state, productList: payload.productList, size: payload.size}
    },
    setShippingList(state: any, {payload}: any) {
      let shippingCartList = state.shippingCartList
      if (state.shippingCartList.find((cart: any) => cart.id === payload.id && cart.size === payload.size)) {
        shippingCartList.map((cart: any) => {
          return {
            ...cart,
            quantity: cart.id === payload.id && cart.size === payload.size ? ++cart.quantity :  cart.quantity
          }
        })
      } else {
        shippingCartList = [{...payload, quantity: 1},...state.shippingCartList]
      }
      return {...state, shippingCartList, shippingCartNum: ++state.shippingCartNum}
    },
    removeProduct(state: any, {payload}: any) {
      return {
        ...state,
        shippingCartList: state.shippingCartList.filter((cart: any) =>
          !(cart.id === payload.id && cart.size === payload.size)),
        shippingCartNum: state.shippingCartNum - payload.quantity
      }
    },
    deleteProduct(state: any, {payload}: any) {
      let shippingCartList = state.shippingCartList
      shippingCartList.map((cart: any) => {
        return {
          ...cart,
          quantity: cart.id === payload.id && cart.size === payload.size ? --cart.quantity :  cart.quantity
        }
      })
      return {
        ...state,
        shippingCartNum: --state.shippingCartNum,
        shippingCartList,
      }
    },
    clearShippingList(state: any, {payload}: any) {
      return {
        ...state,
        shippingCartNum: 0,
        shippingCartList: [],
      }
    }
  },
}
